<template>
  <div class="subject-management">
    <!-- 头部搜索栏 -->
    <div class="header">
      <div class="header-left">
        <div class="title-line"></div>
        <span class="title">学科管理</span>
        <el-input
          v-model="searchQuery"
          placeholder="请输入学科名称"
          class="search-input"
        />
        <el-button class="search-btn" @click="fetchSubjectList">
          <img src="../../assets/images/搜索.png" class="search-icon" alt="搜索" />
          搜索
        </el-button>
      </div>
      <div class="header-right">
        <img 
          src="../../assets/images/加号.png" 
          class="add-btn" 
          @click="handleAddSubject"
          alt="添加学科"
        />
      </div>
    </div>

    <!-- 学科列表 -->
    <div class="subject-list">
      <div 
        class="subject-item" 
        v-for="subject in subjectList" 
        :key="subject.courseId"
      >
        <div class="operate-buttons" :class="{ 'visible': subject.showOperate }">
          <span class="modify-btn" @click="handleModifySubject(subject)">修改</span>
          <span class="delete-btn" @click="handleDeleteSubject(subject)">删除</span>
        </div>
        <div class="subject-name">{{ subject.courseName }}</div>
      </div>
    </div>

    <!-- 添加学科模态框 -->
    <el-dialog v-model="addDialogVisible" title="添加学科" width="400px" :show-close="false">
      <el-form 
        :model="addForm" 
        :rules="formRules" 
        ref="addFormRef" 
        label-width="0"
        hide-required-asterisk
      >
        <el-form-item prop="courseName">
          <el-input
            v-model="addForm.courseName"
            placeholder="请输入学科名称"
            class="subject-input"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="submitAddSubject" class="confirm-btn">确认</el-button>
      </template>
    </el-dialog>

    <!-- 修改学科模态框 -->
    <el-dialog v-model="modifyDialogVisible" title="修改学科" width="400px" :show-close="false">
      <el-form 
        :model="modifyForm" 
        :rules="formRules" 
        ref="modifyFormRef" 
        label-width="0"
        hide-required-asterisk
      >
        <el-form-item prop="courseName">
          <el-input
            v-model="modifyForm.courseName"
            placeholder="请输入学科名称"
            class="subject-input"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modifyDialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="submitModifySubject" class="confirm-btn">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSubject, addSubject, updateSubject, deleteSubject } from '../api/Subject'



// 响应式数据管理
const searchQuery = ref('') // 搜索关键词
const subjectList = ref([]) // 学科列表
const addDialogVisible = ref(false) // 添加模态框状态
const modifyDialogVisible = ref(false) // 修改模态框状态

// 添加表单数据
const addForm = reactive({
  courseName: ''
})

// 修改表单数据
const modifyForm = reactive({
  courseId: '',
  courseName: ''
})

// 2. 表单验证规则（添加/修改通用）
const formRules = reactive({
  courseName: [
    { required: true, message: '请输入学科名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度需在2-10个字符之间', trigger: 'blur' }
  ]
})

// 3. 生命周期钩子：初始化加载学科列表
onMounted(() => {
  fetchSubjectList()
})

// 4. 核心函数
/**
 * 获取学科列表
 */
const fetchSubjectList = async () => {
  try {
    const res = await getSubject('courseList', { search: searchQuery.value })
    if (res.code === 200) {
      // 为每个学科添加showOperate状态（默认显示操作按钮）
      subjectList.value = res.dataset.courseList.map(subject => ({
        ...subject,
        showOperate: true // 初始值改为true（恒显示）
      }))
    }
  } catch (error) {
    ElMessage.error('获取学科列表失败，请重试')
    console.error('获取学科列表失败:', error)
  }
}

/**
 * 打开添加学科模态框
 */
const handleAddSubject = () => {
  // 重置表单
  addForm.courseName = ''
  addDialogVisible.value = true
}

/**
 * 提交添加学科
 */
const submitAddSubject = async () => {
  try {
    const res = await addSubject('addCourse', addForm)
    if (res.code === 200) {
      ElMessage.success('添加学科成功')
      addDialogVisible.value = false
      fetchSubjectList() // 刷新列表
    }
  } catch (error) {
    ElMessage.error('添加学科失败，请重试')
    console.error('添加学科失败:', error)
  }
}

/**
 * 打开修改学科模态框
 */
const handleModifySubject = (subject) => {
  // 填充表单数据
  modifyForm.courseId = subject.courseId
  modifyForm.courseName = subject.courseName
  modifyDialogVisible.value = true
}

/**
 * 提交修改学科
 */
const submitModifySubject = async () => {
  try {
    const res = await updateSubject('updateCourse', modifyForm)
    if (res.code === 200) {
      ElMessage.success('修改学科成功')
      modifyDialogVisible.value = false
      fetchSubjectList() // 刷新列表
    }
  } catch (error) {
    ElMessage.error('修改学科失败，请重试')
    console.error('修改学科失败:', error)
  }
}

/**
 * 删除学科
 */
const handleDeleteSubject = async (subject) => {
  try {
    await ElMessageBox.confirm(
      '确定删除该学科吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const res = await deleteSubject('deleteCourse', { courseId: subject.courseId })
    if (res.code === 200) {
      ElMessage.success('删除学科成功')
      fetchSubjectList() // 刷新列表
    }
  } catch (error) {
    if (error === 'cancel') return // 用户取消删除
    ElMessage.error('删除学科失败，请重试')
    console.error('删除学科失败:', error)
  }
}
</script>

<style scoped>
.subject-management {
  width: 90%;
  margin: 20px auto;
}

/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.title-line {
  width: 2px;
  height: 20px;
  background-color: #007bff;
  margin-right: 10px;
}

.title {
  font-size: 20px;
  margin-right: 20px;
}

.search-input {
  width: 150px;
  margin-right: 10px;
}

:deep(.search-input .el-input__wrapper) {
  border-radius: 12px !important;
}

.search-btn {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  border-radius: 16px;
  padding: 0 15px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.search-icon {
  width: 16px;
  height: 16px;
  margin-right: 5px;
}

.header-right .add-btn {
  width: 25px;
  height: 25px;
  cursor: pointer;
}

/* 学科列表样式 */
.subject-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.subject-item {
  width: 150px;
  height: 150px;
  background-color: #fff;
  border-radius: 25px;
  box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  position: relative;
  cursor: pointer;
}

.subject-item:hover {
  transform: translateY(-5px);
}

.operate-buttons {
  position: absolute;
  top: 10px;
  right: 10px;
  display: none;
  gap: 10px;
}

.operate-buttons.visible {
  display: flex;
}

.modify-btn {
  color: #29a34e;
  cursor: pointer;
}

.delete-btn {
  color: #e83844;
  cursor: pointer;
}

.subject-name {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  text-align: center;
}

/* 模态框样式 */
:deep(.el-dialog) {
  padding: 0;
}

:deep(.el-dialog__header) {
  background-color: #0f6ab1;
  color: #fff;
  text-align: center;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

.subject-input {
  width: 100%;
  text-align: center;
  height: 50px !important;
}

:deep(.el-dialog__footer) {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px;
}

.cancel-btn, .confirm-btn {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  border-radius: 16px;
  padding: 0 20px;
  cursor: pointer;
}
.header[data-v-228da48c]{
    width:95%;
    height:10%;
    padding:0px 30px;
    margin:0 auto;
    background-color: #fff;
    margin-bottom: 20px;
    margin-top: 20px;
    box-shadow: 4px 4px 4px rgba(0, 0, 0, 0.1);
    border-radius: 20px;
    justify-content: space-between;
}
</style>